package com.uziot.bucket.common.util.file;

import com.alibaba.fastjson.util.IOUtils;

import java.io.*;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.StringTokenizer;

/**
 * 文件操作工具类
 * 读、增、删除、复制
 *
 * @author shidt
 * @version V1.0
 * @className FileOperate
 */
public class FileOperate {
    private String message;

    public FileOperate() {
    }

    /**
     * 读取文本文件内容
     *
     * @param filePathAndName 带有完整绝对路径的文件名
     * @param encoding        文本文件打开的编码方式
     * @return 返回文本文件的内容
     */
    public String readTxt(String filePathAndName, String encoding) {
        encoding = encoding.trim();
        StringBuilder str = new StringBuilder();
        String st;
        try {
            FileInputStream fs = new FileInputStream(filePathAndName);
            InputStreamReader isr;
            if ("".equals(encoding)) {
                isr = new InputStreamReader(fs);
            } else {
                isr = new InputStreamReader(fs, encoding);
            }
            BufferedReader br = new BufferedReader(isr);
            try {
                String data;
                while ((data = br.readLine()) != null) {
                    str.append(data).append(" ");
                }
            } catch (Exception e) {
                str.append(e.toString());
            }
            st = str.toString();
        } catch (IOException es) {
            st = "";
        }
        return st;
    }

    /**
     * 新建目录
     * 返回目录创建后的路径
     *
     * @param folderPath 目录
     */
    public void createFolder(String folderPath) {
        try {
            File myFilePath = new File(folderPath);
            if (!myFilePath.exists()) {
                boolean mkdir = myFilePath.mkdir();
            }
        } catch (Exception e) {
            message = "创建目录操作出错";
        }
    }

    /**
     * 多级目录创建
     *
     * @param folderPath 准备要在本级目录下创建新目录的目录路径 例如 c:myf
     * @param paths      无限级目录参数，各级目录以单数线区分 例如 a|b|c
     */
    public void createFolders(String folderPath, String paths) {
        String txts;
        try {
            String txt;
            txts = folderPath;
            StringTokenizer st = new StringTokenizer(paths, "|");
            for (int i = 0; st.hasMoreTokens(); i++) {
                txt = st.nextToken().trim();
                if (txts.lastIndexOf("/") != -1) {
                    createFolder(txts + txt);
                } else {
                    createFolder(txts + txt + "/");
                }
            }
        } catch (Exception e) {
            message = "创建目录操作出错！";
        }
//        return txts;
    }

    /**
     * 新建文件
     *
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @param fileContent     文本文件内容
     */
    public void createFile(String filePathAndName, String fileContent) {
        try {
            File myFilePath = new File(filePathAndName);
            if (!myFilePath.exists()) {
                boolean newFile = myFilePath.createNewFile();
            }
            FileWriter resultFile = new FileWriter(myFilePath);
            PrintWriter myFile = new PrintWriter(resultFile);
            myFile.println(fileContent);
            myFile.close();
            resultFile.close();
        } catch (Exception e) {
            message = "创建文件操作出错";
        }
    }

    /**
     * 有编码方式的文件创建
     *
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @param fileContent     文本文件内容
     * @param encoding        编码方式 例如 GBK 或者 UTF-8
     */
    public void createFile(String filePathAndName, String fileContent, String encoding) {

        try {
            File myFilePath = new File(filePathAndName);
            if (!myFilePath.exists()) {
                boolean newFile = myFilePath.createNewFile();
            }
            PrintWriter myFile = new PrintWriter(myFilePath, encoding);
            myFile.println(fileContent);
            myFile.close();
        } catch (Exception e) {
            message = "创建文件操作出错";
        }
    }

    /**
     * 删除文件
     *
     * @param filePathAndName 文本文件完整绝对路径及文件名
     * @return Boolean 成功删除返回true遭遇异常返回false
     */
    public boolean delFile(String filePathAndName) {
        boolean bea = false;
        try {
            File myDelFile = new File(filePathAndName);
            if (myDelFile.exists()) {
                boolean delete = myDelFile.delete();
                bea = true;
            } else {
                message = (filePathAndName + "删除文件操作出错");
            }
        } catch (Exception e) {
            message = e.toString();
        }
        return bea;
    }

    /**
     * 删除文件夹
     *
     * @param folderPath 文件夹完整绝对路径
     */
    public void delFolder(String folderPath) {
        try {
            //删除完里面所有内容
            boolean b = delAllFile(folderPath);
            File myFilePath = new File(folderPath);
            //删除空文件夹
            boolean delete = myFilePath.delete();
        } catch (Exception e) {
            message = ("删除文件夹操作出错");
        }
    }

    /**
     * 删除指定文件夹下所有文件
     *
     * @param path 文件夹完整绝对路径
     */
    public boolean delAllFile(String path) {
        boolean bea = false;
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (!file.isDirectory()) {
            return false;
        }
        String[] tempList = file.list();
        File temp;
        assert tempList != null;
        for (String s : tempList) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + s);
            } else {
                temp = new File(path + File.separator + s);
            }
            if (temp.isFile()) {
                boolean delete = temp.delete();
            }
            if (temp.isDirectory()) {
                //先删除文件夹里面的文件
                delAllFile(path + "/" + s);
                //再删除空文件夹
                delFolder(path + "/" + s);
                bea = true;
            }
        }
        return bea;
    }

    /**
     * 复制单个文件
     *
     * @param oldPathFile 准备复制的文件源
     * @param newPathFile 拷贝到新绝对路径带文件名
     */
    public void copyFile(String oldPathFile, String newPathFile) {
        try {
            int byteread = 0;
            File oldFile = new File(oldPathFile);
            if (oldFile.exists()) {
                //文件存在时
                InputStream inStream = new FileInputStream(oldPathFile);
                //读入原文件
                FileOutputStream fs = new FileOutputStream(newPathFile);
                byte[] buffer = new byte[10485760];
                while ((byteread = inStream.read(buffer)) != -1) {
                    //字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            message = ("复制单个文件操作出错");
        }
    }

    /**
     * 流复制文件
     *
     * @param inStream    inStream
     * @param newPathFile newPathFile
     * @throws IOException IOException
     */
    public void copyFile(InputStream inStream, String newPathFile) throws IOException {
        int byteread;
        FileOutputStream fs = new FileOutputStream(newPathFile);
        byte[] buffer = new byte[10485760];
        while ((byteread = inStream.read(buffer)) != -1) {
            //字节数 文件大小
            fs.write(buffer, 0, byteread);
        }
        inStream.close();
    }

    /**
     * 复制整个文件夹的内容
     *
     * @param oldPath 准备拷贝的目录
     * @param newPath 指定绝对路径的新目录
     */
    public void copyFolder(String oldPath, String newPath) {
        try {
            //如果文件夹不存在 则建立新文件夹
            boolean mkdirs = new File(newPath).mkdirs();
            File a = new File(oldPath);
            String[] file = a.list();
            File temp;
            assert file != null;
            for (String s : file) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + s);
                } else {
                    temp = new File(oldPath + File.separator + s);
                }
                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()));
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {
                    //如果是子文件夹
                    copyFolder(oldPath + "/" + s, newPath + "/" + s);
                }
            }
        } catch (Exception e) {
            message = "复制整个文件夹内容操作出错";
        }
    }

    /**
     * 移动文件
     *
     * @param oldPath oldPath
     * @param newPath newPath
     */
    public void moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        boolean file = delFile(oldPath);
    }

    /**
     * 移动目录
     *
     * @param oldPath oldPath
     * @param newPath newPath
     */
    public void moveFolder(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }

    public String getMessage() {
        return this.message;
    }

    /**
     * 读本地文件
     *
     * @param filePath filePath
     * @return []
     */
    public static byte[] readFileData(String filePath) {
        File file = new File(filePath);
        FileInputStream fis = null;
        byte[] retByte = new byte[(int) file.length()];
        try {
            fis = new FileInputStream(file);
            int read = fis.read(retByte);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.close(fis);
        }
        return retByte;
    }

    /**
     * 按行读取文件返回list
     *
     * @param filePath filePath
     * @return LinkedList<String>
     * @throws IOException IOException
     */
    public LinkedList<String> readFileLines(String filePath) throws IOException {
        return readFileLines(new File(filePath), null);
    }

    /**
     * 按照行读取文件并存储到List
     *
     * @param file file
     * @return list
     */
    public LinkedList<String> readFileLines(File file, String encoding) throws IOException {
        LinkedList<String> fileList = new LinkedList<>();
        if (!file.exists()) {
            throw new IOException("没有找到对应的文件！");
        }
        try {
            InputStream is = new FileInputStream(file);
            Scanner scan;
            if ("".equals(encoding) || null == encoding) {
                scan = new Scanner(is, "UTF-8");
            } else {
                scan = new Scanner(is, encoding);
            }
            while (scan.hasNextLine()) {
                String line = scan.nextLine();
                if (null != line && !"".equals(line.trim())) {
                    fileList.offer(line.trim());
                }
            }
            is.close();
            scan.close();
        } catch (IOException e) {
            throw new IOException("读取文件发生异常，具体信息为：" + e);
        }
        return fileList;
    }
}
